import { ref } from 'vue'

const GRID_WIDTH = 100
const GRID_HEIGHT = 110
const GRID_GAP = 20

const desktopIcons = ref([])

function snapToGrid(x, y) {
  return {
    left: Math.round(x / GRID_WIDTH) * GRID_WIDTH,
    top: Math.round(y / GRID_HEIGHT) * GRID_HEIGHT
  }
}

function setIcons(icons) {
  // 自动排列初始位置，吸附网格
  desktopIcons.value = icons.map((icon, i) => {
    const col = Math.floor(i / 8)
    const row = i % 8
    return {
      ...icon,
      ...snapToGrid(GRID_GAP + col * GRID_WIDTH, GRID_GAP + row * GRID_HEIGHT)
    }
  })
}

function addIcon(icon) {
  // 新增图标默认放在左上角，吸附网格
  const pos = snapToGrid(20, 20)
  desktopIcons.value.push({ ...icon, ...pos })
}

function moveIcon(fromIndex, toIndex) {
  const arr = desktopIcons.value
  if (fromIndex === toIndex) return
  const moved = arr.splice(fromIndex, 1)[0]
  arr.splice(toIndex, 0, moved)
}

function deleteIcon(iconId) {
  desktopIcons.value = desktopIcons.value.filter(i => i.id !== iconId)
}

function copyIcon(iconId) {
  const icon = desktopIcons.value.find(i => i.id === iconId)
  if (icon) {
    // 复制时偏移一格并吸附网格
    const pos = snapToGrid(icon.left + GRID_WIDTH, icon.top + GRID_HEIGHT)
    const newIcon = { ...icon, id: Date.now(), name: icon.name + ' - 副本', ...pos }
    desktopIcons.value.push(newIcon)
  }
}

function viewIcon(iconId) {
  const icon = desktopIcons.value.find(i => i.id === iconId)
  if (icon) {
    alert(`图标信息：\n名称：${icon.name}\n类型：${icon.type || ''}`)
  }
}

function updateIconPosition(iconId, left, top) {
  const icon = desktopIcons.value.find(i => i.id === iconId)
  if (icon) {
    const snapped = snapToGrid(left, top)
    icon.left = snapped.left
    icon.top = snapped.top
  }
}

export default function useDesktopIcons() {
  return {
    desktopIcons,
    setIcons,
    addIcon,
    moveIcon,
    deleteIcon,
    copyIcon,
    viewIcon,
    updateIconPosition
  }
} 